package com.yang.spingboot.yixincallback.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * 采用MD5加密
 *
 * @author simmon
 * @createDate 2016年12月27日
 */

@Slf4j
public class MD5Utils {
    /**
     * @param param
     * @param key
     * @return java.lang.String
     * @author qiyang
     * @date 2021/12/4 12:14
     * @desc
     */
    public static String createSign(TreeMap<String, Object> param, String key) {
        String orgStr = originalString(param);
        String stringSignTemp = orgStr + key;
        log.debug("签名调试输出：" + stringSignTemp);
        String paysign = MD5Utils.MD5(stringSignTemp);
        return paysign;
    }

    private static String originalString(TreeMap<String, Object> treeMap) {
        log.debug("输入对象:{}", JSON.toJSONString(treeMap));
        Set<Map.Entry<String, Object>> entry = treeMap.entrySet();
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, Object> obj : entry) {
            String k = obj.getKey();
            String v = String.valueOf(obj.getValue());
            if (StringUtils.isEmpty(v)) {
                continue;
            }
            sb.append(k + "=" + v + "&");
        }
        return sb.toString();
    }


    public static String MD5(String data) {
        try {
            // 得到一个信息摘要器
            MessageDigest digest = MessageDigest.getInstance("md5");
            byte[] result = digest.digest(data.getBytes());
            StringBuffer buffer = new StringBuffer();
            // 把没一个byte 做一个与运算 0xff;
            for (byte b : result) {
                // 与运算
                int number = b & 0xff;
                // 加盐
                String str = Integer.toHexString(number);
                if (str.length() == 1) {
                    buffer.append("0");
                }
                buffer.append(str);
                // 标准的md5加密后的结果
                return buffer.toString();
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /***
     * MD5加密 生成32位md5码
     *
     * @param inStr  encode 待加密字符串
     * @return 返回32位md5码
     */
    public static String md5Encode(String inStr, String encode) {
        MessageDigest md5 = null;
        StringBuffer hexValue = null;
        try {
            try {
                md5 = MessageDigest.getInstance("MD5");
            } catch (Exception e) {
                // System.out.println(e.toString());
                e.printStackTrace();
                return "";
            }

            byte[] byteArray = inStr.getBytes(encode);
            byte[] md5Bytes = md5.digest(byteArray);
            hexValue = new StringBuffer();
            for (int i = 0; i < md5Bytes.length; i++) {
                int val = ((int) md5Bytes[i]) & 0xff;
                if (val < 16) {
                    hexValue.append("0");
                }
                hexValue.append(Integer.toHexString(val));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return hexValue.toString();
    }

    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));

        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname)) {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            } else {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
            }
        } catch (Exception exception) {
        }
        return resultString;
    }

    private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
            "e", "f"};

}